package com.zhenyi.zhengfang.interceptor;

import com.cjw.model.DBMap;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.utils.AuthUtils;
import com.youqu.common.model.YqShopUser;
import com.zhengfang.common.model.ZfAdmin;

public class AuthInterceptor  implements Interceptor  {


	private void renderLogin(Controller controller) {
		controller.redirect("/zf/admin/auth");
		
	}

	private String getRequestUrl(Controller controller) {
		String url = controller.getRequest().getRequestURL().toString();
		String queryurl = controller.getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		try {
			controller.setAttr("devMode", PropKit.getBoolean("devMode", false));
			String uid = AuthUtils.getTokenUid(controller);
			if (StrKit.notBlank(uid)) {
				ZfAdmin admin = ZfAdmin.dao.findById(uid);
				if (admin == null) {
					renderLogin(controller);
					return;
				}
				controller.setAttr("userName", admin.getUsername());
				controller.setAttr("userRole", admin.getPassword());

				inv.invoke();
			} else {
				renderLogin(controller);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			DBMap map = new DBMap();
			map.put("status", 500);
			map.put("msg", "出错");
			controller.renderJson(map);
		}
	}

}
